package com.fubon.wloan.util;

import java.util.Base64;
import java.util.Enumeration;
import java.util.Random;

import javax.crypto.Cipher;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.security.*;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

public class RSAUtils {
    public static final String RSA_ALGORITHM = "RSA";
    public static final String RSA_SIGN_ALGORITHM = "SHA256withRSA";
    public static final Charset UTF8 = Charset.forName("UTF-8");


    public static String getRandomString(int length){
		String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		Random random=new Random();
		StringBuffer sb=new StringBuffer();
		for(int i=0;i<length;i++){
		  int number=random.nextInt(62);
		  sb.append(str.charAt(number));
		}
		return sb.toString();
    }
    
    public static KeyPair buildKeyPair() throws NoSuchAlgorithmException {
        final int keySize = 2048;
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(RSA_ALGORITHM);
        keyPairGenerator.initialize(keySize);
        return keyPairGenerator.genKeyPair();
    }

    public static byte[] encrypt(PrivateKey privateKey, String message) throws Exception {
        Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);

        return cipher.doFinal(message.getBytes(UTF8));
    }

    public static byte[] decrypt(PublicKey publicKey, byte[] encrypted) throws Exception {
        Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, publicKey);

        return cipher.doFinal(encrypted);
    }

    /**
     * 从字符串中加载公钥
     *
     */
    public static RSAPublicKey loadPublicKey(String publicKeyPath) throws Exception {
        try {
            FileReader fileReader = new FileReader(publicKeyPath);
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            String line;
            String publicKeyStr = "";
            while((line = bufferedReader.readLine()) != null){
                //System.out.println(line);
                publicKeyStr += line;
            }
            bufferedReader.close();
            fileReader.close();
            byte[] buffer = base64Decode(publicKeyStr);
            KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
            return (RSAPublicKey) keyFactory.generatePublic(keySpec);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeySpecException e) {
            throw new RuntimeException(e);
        }
    }

    public static RSAPrivateKey loadPrivateKey(String privateKeyPath) throws Exception {
        try {
            FileReader fileReader = new FileReader(privateKeyPath);
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            String line;
            String privateKeyStr = "";
            while((line = bufferedReader.readLine()) != null){
                //System.out.println(line);
                privateKeyStr += line;
            }
            bufferedReader.close();
            fileReader.close();
            byte[] buffer = base64Decode(privateKeyStr);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
            KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
            return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeySpecException e) {
            throw new RuntimeException(e);
        } catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }

    public static void savePublicKey(PublicKey publicKey,String filename) throws IOException {
        // 得到公钥字符串
        String publicKeyString = base64Encode(publicKey.getEncoded());
        //System.out.println("publicKeyString=" + publicKeyString);
        FileWriter fw = new FileWriter(filename);
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(publicKeyString);
        bw.close();
    }

    public static void savePrivateKey(PrivateKey privateKey,String filename) throws IOException {
        // 得到私钥字符串
        String privateKeyString = base64Encode(privateKey.getEncoded());
        //System.out.println("privateKeyString=" + privateKeyString);

        BufferedWriter bw = new BufferedWriter(new FileWriter(filename));
        bw.write(privateKeyString);
        bw.close();
    }

    public static String base64Encode(byte[] data) {
        return Base64.getEncoder().encodeToString(data);
    }

    public static byte[] base64Decode(String data) throws IOException {
        return Base64.getDecoder().decode(data);
    }

    /**
     * 签名
     * @param srcData
     * @param privateKeyPath
     * @param privateKeyPwd
     * @return
     */
    public static String sign(String srcData, String privateKeyPath, String privateKeyPwd){

        try {
            PrivateKey  key = null;
            if(privateKeyPwd == null || privateKeyPwd == ""){
            // 从文件中读取私钥
            key = loadPrivateKey(privateKeyPath);
            }else{
            // 获取证书的私钥
            key = readPrivate(privateKeyPath, privateKeyPwd);
            }
            // 进行签名服务
            Signature signature = Signature.getInstance(RSA_SIGN_ALGORITHM);
            signature.initSign(key);
            signature.update(srcData.getBytes(UTF8));
            byte[] signedData = signature.sign();
            return Base64.getEncoder().encodeToString(signedData);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 验签
     * @param srcData
     * @param signedData
     * @param publicKeyPath
     * @return
     */
    public static boolean verify(String srcData, String signedData, String publicKeyPath,boolean flag){
        if(srcData==null || signedData==null || publicKeyPath==null){
            return false;
        }
        try {
            PublicKey publicKey = null;
            if(flag){
                publicKey = loadPublicKey(publicKeyPath);
            }else{
                publicKey = readPublic(publicKeyPath);
            }
            
            Signature sign = Signature.getInstance(RSA_SIGN_ALGORITHM);
            sign.initVerify(publicKey);
            sign.update(srcData.getBytes(UTF8));
            return sign.verify(Base64.getDecoder().decode(signedData));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
    

    /**
     * 从证书读取公钥
     * @param publicKeyPath
     * @return
     */
    private static PublicKey readPublic(String publicKeyPath){
        if(publicKeyPath==null){
            return null;
        }
        PublicKey pk = null;
        FileInputStream bais = null;
        try {
            CertificateFactory certificatefactory = CertificateFactory.getInstance("X.509");
            bais = new FileInputStream(publicKeyPath);
            X509Certificate cert = (X509Certificate)certificatefactory.generateCertificate(bais);
            pk = cert.getPublicKey();
        } catch (CertificateException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally{
            if(bais != null){
                try {
                    bais.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return pk;
    }
    
    /**
     * 从证书读取私钥
     * @param path
     * @return
     */
    private static PrivateKey readPrivate(String privateKeyPath, String privateKeyPwd){
        if(privateKeyPath==null || privateKeyPwd==null){
            return null;
        }
        InputStream stream = null;
        try {
            // 获取JKS 服务器私有证书的私钥，取得标准的JKS的 KeyStore实例
            KeyStore store = KeyStore.getInstance("JKS");
            stream = new FileInputStream(new File(privateKeyPath));
            // jks文件密码，根据实际情况修改
            store.load(stream, privateKeyPwd.toCharArray());
            // 获取jks证书别名
            Enumeration en = store.aliases();
            String pName = null;
            while (en.hasMoreElements()) {
                String n = (String) en.nextElement();
                if (store.isKeyEntry(n)) {
                    pName = n;
                }
            }
            // 获取证书的私钥
            PrivateKey key = (PrivateKey) store.getKey(pName,
                    privateKeyPwd.toCharArray());
            return key;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(stream != null){
                try {
                    stream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public static void main(String[] args) throws Exception {
        // generate public and private keys
        KeyPair keyPair = buildKeyPair();
        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();
        savePrivateKey(privateKey,"/Users/HY_LOAN/Desktop/rsakey/privateKey2.keystore");
        savePublicKey(publicKey, "/Users/HY_LOAN/Desktop/rsakey/publicKey2.keystore");
        // encrypt the message
        byte[] encrypted = encrypt(privateKey, "This is a secret message");
        System.out.println(base64Encode(encrypted)); // <<encrypted message>>

        // decrypt the message
        byte[] secret = decrypt(publicKey, encrypted);
        System.out.println(new String(secret, UTF8)); // This is a secret message


    }

}